package game.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Server {
	private boolean run = true;
	private Socket socket;
	private BufferedReader input;
	private PrintStream output;

	public static final int CONNECT_ID = 1;
	public static final int DISCONNECT_ID = 2;
	public static final int POS_ID = 3;
	public static final int NAME_ID = 4;
	
	private String ip = "localhost";
	private String name = "Bob";
	private int port = 26646;
	
	public Server(String name, String ip, int port) {
		this.name = name;
		this.ip = ip;
		this.port = port;
	}

	public void connect()  {
		if (System.console() == null) {
			return;
		}
		
		try {
			socket = new Socket(ip, port);
		} catch (Exception e) {
			System.out.println("Failed to connect to server!");
			System.exit(1);
		}

		try {
			input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			output = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}

		send(NAME_ID + "," + name);
		new Thread(new Runnable() {
			public void run() {
				while (run) {
					String s = "";
					try {
						if (!socket.isClosed()) {
							s = input.readLine();
						}

						if (!s.equals("")) {
							System.out.println(s);
						}
						Thread.sleep(1);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	
	public void send(String data) {
		output.println(data);
	}

	public void disconnect() throws Exception {
		run = false;
		input.close();
		output.close();
		socket.close();
	}
}
